package com.xln.furns.web;

import com.google.gson.Gson;
import com.xln.furns.entity.Member;
import com.xln.furns.service.LoginService;
import com.xln.furns.service.impl.LoginServiceimpl;
import com.xln.furns.service.MemberService;
import com.xln.furns.service.impl.MemberServiceimpl;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * 该servlet处理与Member相关的请求
 */
public class MemberServlet extends BasicServlet {

    MemberService memberService = new MemberServiceimpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

//    @Override
//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String action = request.getParameter("action");
//        if (action.equals("login")){
//            login(request,response);
//
//        } else if (action.equals("register")) {
//            register(request,response);
//        }else {
//            System.out.printf("参数请求错误！");
//        }
//    }

    /**
     * 处理登入
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // System.out.printf("调用了Loginservler方法！");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        LoginService loginService = new LoginServiceimpl();
        String code = request.getParameter("code");
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
       //立即移除session验证码，防止重复使用
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
//        if (token != null && token.equalsIgnoreCase(code)) {
            if (loginService.login(new Member(null, username, password, null)) == null) {
                //把登录错误信息，放入到请求域=>如果忘了，可以看Servlet/jsp
                request.setAttribute("msg", "用户名或者密码错误！");
                request.setAttribute("username", username);
                request.getRequestDispatcher("/views/member/login.jsp").
                        forward(request, response);

            } else {
                Member member = loginService.login(new Member(null, username, password, null));
                request.getSession().setAttribute("member", member);
                request.getRequestDispatcher("/views/member/login_ok.jsp").
                        forward(request, response);

            }
//        }else {
//            request.setAttribute("msg","验证码不正确！");
//            request.getRequestDispatcher("/views/member/login_ok.jsp").
//                    forward(request, response);
//        }
    }


    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());

    }

    /**
     * 处理注册
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //立即移除session验证码，防止重复使用
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if (token != null && token.equalsIgnoreCase(code)) {
            MemberService memberService = new MemberServiceimpl();
            Member member = new Member(null, username, password, email);
            if (!memberService.isExistsUsername(username)) {
                if (memberService.registerMember(member)) {
                    //System.out.printf("注册成功");
                    //请求转发 知识点：servelt-----------------------------------------------------------
                    request.getRequestDispatcher("/views/member/register_ok.jsp")
                            .forward(request, response);
                } else {
                    //System.out.printf("注册失败");
                    request.getRequestDispatcher("/views/member/register_fail.html")
                            .forward(request, response);

                }
                //System.out.printf("不存在  2");
            } else {

                //System.out.printf("用户存在  1");
                request.getRequestDispatcher("/views/member/login.jsp")
                        .forward(request, response);
            }
        }else {
            request.setAttribute("active","register");
            request.setAttribute("msg","验证码错误！");
            request.setAttribute("username",username);
            request.setAttribute("email",email);

            request.getRequestDispatcher("/views/member/login.jsp")
                    .forward(request, response);
        }
    }

    /**
     * 验证码异步请求（光标移走后开始处理）
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void token(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String code = request.getParameter("code");
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //立即移除session验证码，防止重复使用
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        boolean tokenJson = token.equalsIgnoreCase(code);
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("tokenCheck",tokenJson);
        String resultJson = new Gson().toJson(tokenMap);
        response.getWriter().write(resultJson);
    }

    /**
     * ajax验证注册用户名是否存在（光标移走后开始处理）
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void isExistUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        boolean existsUsername = memberService.isExistsUsername(username);

//        String resultJosn = "{\"isExist\":"+existsUsername+"}";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isExist",existsUsername);
//        resultMap.put("email","xln@123.com");
        String resultJosn = new Gson().toJson(resultMap);
        resp.getWriter().write(resultJosn);

    }
}
